<template>
  <n-dropdown :options="options" @select="handleSelect">
    <div class="flex cursor-pointer items-center">
      <n-avatar round :size="36" :src="userStore.avatar || defaultUser" />
      <div v-if="userStore.userInfo" class="ml-12 flex-col flex-shrink-0 items-center">
        <span class="text-14">{{ userStore.username }}</span>
        <span class="text-12 opacity-50">[{{ userStore.roleName }}]</span>
      </div>
    </div>
  </n-dropdown>
</template>

<script setup>
import defaultUser from '@/assets/default-user.png'
import { useUserStore, useAuthStore } from '@/store'
import * as userApi from '@/api/user'

const userStore = useUserStore()
const authStore = useAuthStore()

const options = reactive([
  {
    label: '退出登录',
    key: 'logout',
    icon: () => h('i', { class: 'i-mdi:exit-to-app text-14' }),
  },
])

function handleSelect(key) {
  switch (key) {
    case 'logout':
      $dialog.confirm({
        title: '提示',
        type: 'info',
        content: '确认退出？',
        async confirm() {
          try {
            await userApi.logout()
          } catch (error) {
            console.error(error)
          }
          authStore.logout()
          $message.success('已退出登录')
        },
      })
      break
  }
}
</script>
